<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/3
 * Time: 10:53
 */

namespace app\applet\model;


use think\Db;
use think\Exception;

class Payment
{
   public function orderNodify($input){
       $orderSn=$input['order_sn'];
       //获取订单信息
       $orderInfo=Db::name("order")->where(['order_Sn'=>$orderSn])
           ->field("order_id,member_id,is_del,status,pay_status,order_score_money,
           order_coin_money,order_delivery_fee,wx_money,score_money,coin_money")->find();
       $orderId=$orderInfo['order_id'];
       if($orderInfo['status']!=2&&$orderInfo['is_del']==2){
           if(($orderInfo['order_coin_money']+$orderInfo['order_delivery_fee'])==($orderInfo['coin_money']+$orderInfo['wx_money']+$orderInfo['score_money'])){//订单金额判断
               $member_id=$orderInfo['memeber_id'];
               $coin_money=$orderInfo['coin_money'];
               $score_money=$orderInfo['score_money'];
               if($score_money>0) {
                   $cmp_score_money=Db::name("member_asset_log")
                       ->where(['member_id'=>$member_id,'log_type_id'=>53,'relation_id'=>$orderId])->value("amount");
                   if($cmp_score_money!=$coin_money){
                       returnJson(-2004,"订单异常");
                   }
               }
               if($coin_money>0){
                   $cmp_coin_money=Db::name("member_asset_log")
                       ->where(['member_id'=>$member_id,'log_type_id'=>54,'relation_id'=>$orderId])->value("amount");
                   if($coin_money!=$cmp_coin_money){
                       returnJson(-2004,"订单异常");
                   }
                   
               }
               Db::startTrans();
               try{
                   $updOrder=['status'=>'2','pay_status'=>2,'pay_time'=>time(),'is_del'=>1,'update_time'=>time()];

                   //获取配送方式
                   $d_method=Db::name("order_goods")->where(['order_id'=>$orderId])->sum("d_method");
                   if($d_method==0){
                       $updOrder['status']=4;
                       Db::name("order_goods")->where(['order_id'=>$orderId])->update(['og_d_status'=>4]);

                   }
                   Db::name("member_asset_log")->where(['member_id'=>$member_id,'log_type_id'=>['in',[53,54]],'relation_id'=>$orderId])->delete();
                   //更新订单状态
                   Db::name("order")->where(['order_id'=>$orderId])->update( $updOrder);
                   if($coin_money>0||$score_money>0){
                       $sql="update mm_member_asset set frozen_score=frozen_score-$score_money,pay_frozen_score=pay_frozen_score-$score_money,frozen_coin=frozen_coin-$coin_money where member_id=".$member_id."and frozen_score>=$score_money  and pay_frozen_score>=$score_money and frozen_coin>=$coin_money ";
                       Db::query($sql);
                   }

                   Db::commit();
                   returnJson(200,'订单创建成功');
               }catch (Exception $e){
                   Db::rollback();
                   returnJson(-2004,"订单创建失败");
               }
           }
       }

   }

    /**
     * @param $input
     * 支付成功
     */
   public function orderSuccess($input){
       $order_sn=$input['order_sn'];
       //获取订单信息
       $orderInfo=Db::name("order")->where(['order_sn'=>$order_sn])->field("order_id,member_id,order_score_money,store_id,order_delivery_fee,order_coin_money,status,pay_status,create_time,pay_time,source_type")->find();
       $store_name=Db::name("store_apply")->where(['sa_id'=> $orderInfo['store_id']])->value("company_name");
        $member_id=$orderInfo['member_id'];


       $orderSpecList=Db::name("order_goods")->where(['order_id'=>$orderInfo['order_id']])
           ->field("og_id,goods_id,goods_num,score_money,coin_money,spec_name,
           spec_pic,goods_name,delivery_fee,create_time")->select();
       $tm=time();
       $messageInfo=[];
       $nickName=Db::name("member")->where(['member_id'=>$member_id])->value("nickName");
       foreach ($orderSpecList as &$spec) {
           $spec['order_sn'] = $order_sn;
           $spec['pay_time'] = $orderInfo['pay_time'];
           if (!in_array($orderInfo["source_type"], [2, 3])) {
               $gType=Db::name("goods")->where(['goods_id'=>$spec['goods_id']])->value("g_type");
           }
           if (in_array($orderInfo["source_type"], [2, 3])) {
               $source = Db::name("choice_goods")->where(['goods_id' => $spec['goods_id']])->value("source");
               if ($source == 2) {
                   $spec['store_name'] = "京东商城";
               } elseif ($source == 6) {
                   $spec['store_name'] = "阿里巴巴";
               } elseif ($source == 7) {
                   $spec['store_name'] = "天猫商城";
               } else {
                   $spec['store_name'] = "第三方商城";
               }

           } elseif ($orderInfo["source_type"] == 4|| $gType==2) {//干货分享
               if($orderInfo["source_type"] == 4){
                   $spec['store_name'] = "自营店铺";
               }
               //获取商品详情
               $nums = Db::name("goods_member_grade")->where(['member_id' => $member_id, 'goods_id' => $spec['goods_id']])->count();
               if (empty($nums)) {
                   $gmGrade = ['member_id' => $member_id, 'goods_id' => $spec['goods_id'], 'member_grade' => 1, 'create_time' => $tm, 'update_time' => $tm];
                   $num = Db::name("goods_member_grade")->insert($gmGrade);
                   if ($num <= 0) {
                       throw new Exception("更新失败2");
                   }
               }
               //获取当前会员等级
               $goods_member_grade = Db::name("goods_member_grade")->where(['member_id' => $member_id, 'goods_id' => $spec['goods_id']])->value("member_grade");
               //判断当前订单是否升级
               $orderAmount = $spec['score_money'] * $spec['goods_num']+ $spec['coin_money'] * $spec['goods_num'];

               $goodsInfo=Db::name('goods_info')->where(['goods_id' => $spec['goods_id']])->field("copper_money,silver_money,gold_money")->find();


               $copper_money = $goodsInfo['copper_money'];
               $silver_money = $goodsInfo['silver_money'];
               $gold_money = $goodsInfo['gold_money'];

               if ($orderAmount >= $gold_money&&$gold_money>0) {
                   $grade = 4;
                   $gradeName='金客';
               } elseif ($orderAmount >= $silver_money&&$silver_money>0) {
                   $grade = 3;
                   $gradeName='银客';
               } elseif ($orderAmount >= $copper_money&&$copper_money>0) {
                   $grade = 2;
                   $gradeName='铜客';
               } else {
                   $grade = 1;
               }
               $new_goods_member_grade = $goods_member_grade > $grade ? $goods_member_grade : $grade;
               //获取上级会员等级
               $inviter_id=Db::name("goods_member_inviter")->where(['member_id'=>$member_id,'goods_id'=>$spec['goods_id']])->value("inviter_id");
               if( $inviter_id>0){
                   $direct_member_grade=Db::name("goods_member_grade")->where(['member_id'=>$inviter_id,'goods_id'=>$spec['goods_id']])->value("member_grade");
               }
               $nums=Db::name("message")->where(["member_id"=>$member_id,'og_id'=>$spec['og_id']])->count();
               if(empty($nums)){
                   Db::startTrans();
                   try{
                       if ($goods_member_grade < $grade) {//会员需要升级
                           //$msgTitle="你的消费额已达到".$gradeName."资格";
                           $msgTitle="会员升级通知！";
                           if( $inviter_id>0){//存在上级
                               $content="请联系你的推介人(电话)请他在其会员中心-我的消息-系统消息里帮你确认".$gradeName."资格的升级,只有这样你才能享受相应的分享佣金。";

                               $invtcontent="你邀请推介的会员 ".$nickName."，已购买的".$spec['goods_name'].$orderAmount ."元裂变爆品，请点击下方按钮，帮对方升级为".$gradeName;

                               //$msgNTitle="我将要升级成为".$gradeName."会员，请点击此消息帮我确认升级！";
                               $msgNTitle="会员升级通知！";


                               $message=["member_id"=>$member_id,'title'=>$msgNTitle,'content'=>$invtcontent,
                                   'create_time'=>$tm,'update_time'=>$tm,'object_type'=>2,"object_arr"=>$inviter_id,
                                   'class_type'=>14,'exm_status'=>1,'og_id'=>$spec['og_id'],'msg_type'=>2];

                               $msgInvtId=Db::name("message")->insertGetId( $message);

                           }else{//不存在上级
                               if( $gType!=2){
                                   $content="恭喜您，购买【".$spec['goods_name']."】消费额已达到".$gradeName."资格,系统会为您升级为".$gradeName."会员";
                               }else{
                                   $content="恭喜您，购买的【".$spec['goods_name']."】消费额已达到".$gradeName."资格,确认收货后7天，系统会为您升级为".$gradeName."会员";
                               }
                           }
                           $message=["member_id"=>$member_id,'title'=>$msgTitle,'content'=>$content,
                               'create_time'=>$tm,'update_time'=>$tm,'object_type'=>2,"object_arr"=>$member_id,
                               'class_type'=>14,'og_id'=>$spec['og_id']];

                           $msgId=Db::name("message")->insertGetId( $message);
                       }
                       Db::commit();
                   }catch (Exception $e){
                       Db::rollback();
                   }
               }


           }else{
               $spec['store_name']=$store_name;
           }
           unset($spec['goods_id']);
       }
       if(!empty($msgId)&&$msgId>0){
           $messageInfo=Db::name("message")->find($msgId);
           $messageInfo['grade']=$grade;
       }
       return ['goods_list'=>$orderSpecList,'order_coin_money'=>$orderInfo['order_coin_money'],
           'order_score_money'=>$orderInfo['order_score_money'],'message'=>$messageInfo];

   }
}